﻿using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using DimensionsHelper.ExcelAddIn.Core;
using Microsoft.Web.WebView2.Core;

namespace DimensionsHelper.ExcelAddIn.Ms.Controls
{
    public partial class SettingWindow : Form
    {
        private const string HtmlResource = "DimensionsHelper.ExcelAddIn.Ms.Controls.index.html";

        private static CoreWebView2Environment _env;

        public static async Task<CoreWebView2Environment> GetEnvironment(bool allowNullValue = false)
        {
            if (_env == null && !allowNullValue)
            {
                _env = await CoreWebView2Environment.CreateAsync(
                    userDataFolder: Path.Combine(ExcelAddInEnv.UserDataFolder, "User Data"));
            }

            return _env;
        }

        public SettingWindow()
        {
            InitializeComponent();
            MainWebView.CoreWebView2InitializationCompleted += MainWebView_CoreWebView2InitializationCompleted;
            Load += SettingWindow_Load;
        }

        
        private async void SettingWindow_Load(object sender, EventArgs e)
        {
            try
            {
                await MainWebView.EnsureCoreWebView2Async(await GetEnvironment());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void MainWebView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
        {
            if (!e.IsSuccess)
            {
                return;
            }

            var settings = MainWebView.CoreWebView2.Settings;
            settings.AreDevToolsEnabled = false;
            settings.AreDefaultContextMenusEnabled = false;
            settings.AreDefaultScriptDialogsEnabled = false;
            settings.IsStatusBarEnabled = false;
            settings.IsWebMessageEnabled = true;
            settings.IsZoomControlEnabled = false;
            settings.AreBrowserAcceleratorKeysEnabled = false;

            var assembly = typeof(SettingWindow).Assembly;
            using (var stream = assembly.GetManifestResourceStream(HtmlResource))
            {
                if (stream != null)
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var htmlContent = reader.ReadToEnd();
                        MainWebView.NavigateToString(htmlContent);
                    }
                }
                else
                {
                    throw new FileNotFoundException($"Resource '{HtmlResource}' not found.");
                }
            }
        }
    }
}
